package global

import (
	"gorm.io/gorm/logger"
	"k8s-admin/models"
	"os"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	GORM *gorm.DB
	err  error
)

func InitMysql() {
	dsn := viper.GetString("Database.DBUSER") +
		":" + viper.GetString("Database.DBPASS") +
		"@tcp(" + viper.GetString("Database.DBHOST") +
		":" + viper.GetString("Database.DBPORT") + ")" +
		"/" + viper.GetString("Database.DBNAME") +
		"?charset=utf8mb4&parseTime=True&loc=Local"

	GORM, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic("数据库连接失败" + err.Error())
	}
	if viper.GetInt("mysql.ActiveDebug") == 1 {
		GORM = GORM.Debug()
	}
	// 开启连接池
	db, _ := GORM.DB()
	db.SetMaxIdleConns(10)
	db.SetMaxOpenConns(100)
	TPLogger.Info("数据库初始化成功!!!")
}

// 初始化数据库表
func InitMysqlTables() {
	err = GORM.AutoMigrate(models.Configs{}, &models.Dept{}, &models.Role{}, &models.User{}, &models.Casbin{})
	if err != nil {

		TPLogger.Error("生成数据表失败", err)
		os.Exit(0)
	}
}
